//
//  NetWorkTools.swift
//  Swift封装 AFN 网络工具
//
//  Created by 张鹏飞 on 09/8/20.
//  Copyright © 2009年 张鹏飞. All rights reserved.
//

import UIKit
import AFNetworking

 /// Http请求方法枚举
enum PFRequestMethod: String {

    case GET = "GET"
    case POST = "POSt"
}

//MARK: 网络工具
class NetWorkTools: AFHTTPSessionManager {
    
    /// MARK: - 应用程序信息
    private let appKey = "3296173898"
    private let appSecret = "bd0c51b6f24f3402588e0e40828aee59"
    private let redirectUrl = "http://www.baidu.com"
    
 /// 网络请求完成回调 
    typealias PFRequestCallBack = (result:AnyObject?, error: NSError?) -> ()
    
    //单例
    static let sharedTools: NetWorkTools = {
        let tools = NetWorkTools(baseURL: nil)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
        
        }()
    
///返回字典 token
    private var tokenDict: [String: AnyObject]? {
    
        //判断 token 是否有效
        if let token = UserAccountViewModel.sharedUserAccount.accessToken {
        
            return["access_token": token]
        }
        return nil
    }

}

// MARK: - 微博数据相关方法
extension NetWorkTools {

    func loadStatus(finished: PFRequestCallBack) {
    
        //1. 获取 token 字典
            guard let params = tokenDict else {
        
            //如果字典为 nil 通知调用方,token 无效
            finished(result: nil, error: NSError(domain: "ERROR", code: -1001, userInfo: ["access_token": "token 为空"]))
            return
            }
        //2. 准备网络参数
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //3.发起网络请求
        request(.GET, URLString: urlString, parameters: params, finish: finished)
    }
    
}

// MARK: - 用户相关方法
extension NetWorkTools {

    /// 获取用户信息
    ///
    /// - parameter uid:         uid
    /// - parameter acessToken:  acessToken
    /// - parameter finished:    完成回调
    /// - see:[http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    func loadUserInfo(uid: String, finished: PFRequestCallBack) {
    
        //获取 token 字典
        guard var params = tokenDict else {
        
            //如果字典为 nil 通知调用方,token 无效
            finished(result: nil, error: NSError(domain: "ERROR", code: -1001, userInfo: ["access_token": "token 为空"]))
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        params["uid"] = uid
       
        request(.GET, URLString: urlString, parameters: params, finish: finished)
        
    }
}
///MARK: - OAuth 相关方法
extension NetWorkTools {

    //extension中不能定义存储型属性
      //oauth 授权 URL(计算型属性)
    var oauthURL: NSURL {
    
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlString)!
    }
    
    ///加载 AcrossToken
    func loadAccessToken(code: String,finish: PFRequestCallBack) {
    
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        request(.POST, URLString: urlString, parameters: params, finish: finish)
        
        //测试返回的数据格式
        //1.设置相应的数据格式是二进制格式
//        responseSerializer = AFHTTPResponseSerializer()
//        //2.发起网络请求
//        POST(urlString, parameters: params, success: { (_, result) -> Void in
//            //将二进制数据转换成字符串
//            let json = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
//            print(json)
//            }, failure: nil)
    }
}

//MARK: - 封装 AFN 网络方法
extension NetWorkTools {

   private func request(method: PFRequestMethod, URLString: String, parameters: [String: AnyObject]?,finish: PFRequestCallBack) {
        
        //定义成功回调
        let success = {(task: NSURLSessionDataTask, result: AnyObject?) -> Void in
        
            finish(result: result, error: nil)
        }
        //失败回调
        let failure = {(task: NSURLSessionDataTask?, error: NSError) -> Void in
            print(error)
            finish(result: nil, error: error)
        }
        if method == PFRequestMethod.GET {
        
            GET(URLString, parameters: parameters, success: success, failure: failure)
        }else{
        
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }

    
      
}
}